package com.wkn.wknAdmin.service.impl;

import com.wkn.wknAdmin.entity.Menu;
import com.wkn.wknAdmin.entity.Role;
import com.wkn.wknAdmin.entity.User;
import com.wkn.wknAdmin.entity.dto.UserDto;
import com.wkn.wknAdmin.mapper.RoleMapper;
import com.wkn.wknAdmin.mapper.RoleMenuMapper;
import com.wkn.wknAdmin.mapper.UserMapper;
import com.wkn.wknAdmin.result.ResultVO;
import com.wkn.wknAdmin.service.MenuService;
import com.wkn.wknAdmin.service.UserService;
import com.wkn.wknAdmin.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title:
 * @Description:
 * @Author: WKN
 * CreateDate: 2022/8/12 0:43
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuService menuService;

    ResultVO result = new ResultVO();

    /**
     * 登  录
     * -1 为用户不存在
     * 0  为密码错误
     * 1  登录成功
     *
     * @param userDto
     * @return
     */
    @Override
    public ResultVO login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return result.Fail("用户名或密码不能为空");
        }
        UserDto dto = userMapper.login(userDto);
        if (dto != null) {
            String token = TokenUtils.getToken(dto.getId().toString(), dto.getPassword());
            dto.setToken(token);


            String roleName = dto.getRole();
            Role role = roleMapper.getOne(roleName);
            Integer id = role.getId();
            // 得到对应角色id的所有菜单id
            List<Integer> roleMenuIds = roleMenuMapper.getRoleMenu(id);
            if(CollectionUtils.isEmpty(roleMenuIds)) {
                return result.Fail("当前用户无任何权限，请先分配权限");
            }

            List<Menu> resultMenu = menuService.findMenuByIds(roleMenuIds);

            List<Menu> parents = resultMenu.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());

            // 找出一级菜单的子菜单
            for(Menu menu : parents){
                menu.setChildren(resultMenu.stream().filter(m -> menu.getId().equals(m.getPid())).collect(Collectors.toList()));
            }

            dto.setMenus(parents);

            return result.Success(dto);
        }
        return result.Fail("用户名或密码错误");
    }


    /**
     * 查询单个用户
     *
     * @param username
     * @return
     */
    @Override
    public User getOne(String username) {
        return userMapper.getOne(username);
    }

    @Override
    public User getById(String id) {
        return userMapper.getById(id);
    }

    /**
     * 获取全部用户
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }


    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteById(id);
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public int batchDelete(List<Integer> ids) {
        return userMapper.batchDelete(ids);
    }


    /**
     * 更新或添加用户
     *
     * @param user
     * @return
     */
    @Override
    public ResultVO save(User user) {
        String username = user.getUsername();
        User getUser = userMapper.getOne(username);
        if (user.getId() == null) {
            if (getUser != null) {
                return result.Fail("用户名已存在");
            }
            int insert = userMapper.insert(user);
            return insert > 0 ? result.Success("添加成功") : result.Fail("添加失败");
        }
        int update = userMapper.update(user);
        return update > 0 ? result.Success("修改成功") : result.Fail("修改失败");
    }


    /**
     * 分页查询用户
     *
     * @param pageNum  当前页码
     * @param pageSize 每一页展示数据的条数
     * @return
     */
    @Override
    public List<User> selectPage(Integer pageNum, Integer pageSize, String username) {
        List<User> users = userMapper.selectPage(pageNum, pageSize, username);
        return users;
    }


    /**
     * 获取记录数
     *
     * @return
     */
    @Override
    public int getTotalCount(String username) {
        return userMapper.getTotalCount(username);
    }
}
